//
//  PhotoBrowerViewController.swift
//  MyWeibo
//
//  Created by 余丽丽 on 15/10/20.
//  Copyright © 2015年 余丽丽. All rights reserved.
//

import UIKit
import SVProgressHUD

let PhotoCellIdentifier = "PhotoCell"


class PhotoBrowerViewController: UIViewController {

      var token:dispatch_once_t = 0
    
    private var screenBounds = UIScreen.mainScreen().bounds
    
    private var urls: [AnyObject]
    private var imgIndex: Int = 0
    
    
    let PhotoCollectionLayout = UICollectionViewFlowLayout()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orangeColor()
        // Do any additional setup after loading the view.
        
    }
    
    ///  构造函数
    override func loadView() {
        
       screenBounds.size.width += 20
        view = UIView(frame: screenBounds)
        
        setupUI()
        prepareCollectionView()
        btnAddTarget()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    init(urls:[AnyObject],index: Int){
        self.urls = urls
        self.imgIndex = index
        //调用父类的构造方法
        // TODO:|为什么用这个方法?
        super.init(nibName: nil, bundle: nil)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }

    ///  设置界面
    private func setupUI(){
    
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        saveButton.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 100, height: 32), offset:CGPoint(x: 8, y: -8))
        closeButton.ff_AlignInner(type: ff_AlignType.BottomRight, referView: view, size: CGSize(width: 100, height: 32), offset: CGPoint(x: -8, y: -8))
        
        //设置collectioniew的layout属性
        setupLayout()
        
    }
    
    //设置collectionView的布局
    private func setupLayout(){
        
        PhotoCollectionLayout.itemSize = view.bounds.size
        PhotoCollectionLayout.minimumInteritemSpacing = 0
        PhotoCollectionLayout.minimumLineSpacing = 0
        PhotoCollectionLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //分页
        collectionView.pagingEnabled = true
  
    }
    
    //设置collectionView的属性
    private func prepareCollectionView(){
        //注册cell
        collectionView.registerClass(PhotoBrowerCell.self, forCellWithReuseIdentifier: PhotoCellIdentifier)
        
        //设置代理和数据源代理
        collectionView.dataSource = self
        collectionView.delegate = self
        
 
    }
    
    private func btnAddTarget(){
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
    
    }
    
    func currentIndexPath() -> NSIndexPath{
        return collectionView.indexPathsForVisibleItems().last!
    }
    
    ///  保存
    @objc private func save(){
    //获取当前图片
        let indexPath = currentIndexPath()
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowerCell
        guard let image = cell.photoImg.image else{
            return
        }
        
        //保存
        UIImageWriteToSavedPhotosAlbum(image, self, "didSaveImage:error:contextInfo:", nil)
    
    
    }
    
    func didSaveImage(image:UIImage,error:NSError?,contextInfo:AnyObject?){
        let msg = (error == nil ? "保存成功" : "保存失败")
        SVProgressHUD.showInfoWithStatus(msg)
        
    
    }
    ///  关闭
    @objc private func close(){
    
        // 保存转场视图
        let cell = collectionView.cellForItemAtIndexPath(currentIndexPath()) as! PhotoBrowerCell
        PopFromView = cell.photoImg
       
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("HAHAH ")
        print(token)
        //因为只有第一次需要设置跳转,所以下面的方法只被执行一次
        dispatch_once(&token) { () -> Void in
           //跳转到用户选中的照片
            let indexPath = NSIndexPath(forItem: self.imgIndex, inSection: 0)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
          print("我来啦")
            
        }
    }
    
  
    
    private lazy var collectionView: UICollectionView = UICollectionView(frame:self.screenBounds, collectionViewLayout: self.PhotoCollectionLayout)
    private lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14.0, color: UIColor.whiteColor(), backColor: UIColor.grayColor())
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14.0, color: UIColor.whiteColor(), backColor: UIColor.grayColor())
}

    extension PhotoBrowerViewController: UICollectionViewDataSource, UICollectionViewDelegate{
    
        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return urls.count
        }
        
        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoCellIdentifier, forIndexPath: indexPath) as! PhotoBrowerCell
           cell.imgURL = NSURL(string: urls[indexPath.item] as! String)
            cell.backgroundColor = UIColor.clearColor()
            return cell
        }
         
    
    }
    
    
    
    

